﻿namespace Api.Controllers;

/// <summary>
/// 控制器父类
/// </summary>
[XSSFilter]
[SqlInjectFilter]
public class BaseController : ControllerBase
{
    /// <summary>
    /// 判断是否是移动端字符串
    /// </summary>
    public static string MobileReg = string.Empty;

    /// <summary>
    /// 当前用户私有信息
    /// </summary>
    private CurrentUser _currentUser;
    private IOperationLogBLL _operationLogBLL;
    /// <summary>
    /// 导入录制计划锁
    /// </summary>
    public static readonly object ImportRecordPlanLock = new object();
    /// <summary>
    /// 无参构造函数
    /// </summary>
    public BaseController() { }
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="operationLogBLL"></param>
    public BaseController(IOperationLogBLL operationLogBLL)
    {
        _operationLogBLL = operationLogBLL;
    }
    /// <summary>
    /// Excel 任务
    /// </summary>
    public static Dictionary<string, ExcelTaskModel> excelTasks = new Dictionary<string, ExcelTaskModel>();
    /// <summary>
    /// 当前用户信息
    /// </summary>
    protected CurrentUser CurrUser
    {
        get
        {
            IUserBLL userBLL = IocManager.Resolve<IUserBLL>();
            IRoleBLL roleBLL = IocManager.Resolve<IRoleBLL>();
            var userVM = new UserVM
            {
                Id = Convert.ToInt32(this.Request.HttpContext?.User.FindFirstValue("user_id")),
                Name = this.Request.HttpContext?.User.FindFirstValue("name") ?? ""
            };
            var user = userBLL.Get(x => x.UserId == userVM.Id);
            if (user != null)
            {
                var role = roleBLL.Get(x => x.Id == user.RoleId);
                _currentUser = new CurrentUser
                {
                    Id = user.Id,
                    UserId = user.UserId,
                    Account = user.Account,
                    Name = user.Name,
                    RoleId = user.RoleId,
                    Type = user.Type,
                    Gender = user.Gender,
                    Avatar = user.Avatar,
                    Enable = user.Enable,
                };
                if (role != null)
                {
                    _currentUser.RoleName = role.Name;
                }
            }
            return _currentUser;
        }
    }

    /// <summary>
    /// 执行有返回数据
    /// </summary>
    /// <param name="func"></param>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected ResultModel<T> OperationExecuteReturnData<T>(Func<T> func, AddOperationLogInput? operationLog = null)
    {
        ResultModel<T> resultModel = new ResultModel<T>();
        try
        {
            resultModel.data = func();
            resultModel.code = 1;
            UserOperationLog(operationLog);
        }
        catch (Exception ex)
        {
            Log.WriteException(ex);
            resultModel.code = -1;
            resultModel.msg = ex.Message;
        }

        return resultModel;
    }

    /// <summary>
    /// 执行有返回数据
    /// </summary>
    /// <param name="func"></param>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected async Task<ResultModel<T>> OperationExecuteReturnDataAsync<T>(Func<Task<T>> func, AddOperationLogInput? operationLog = null)
    {
        return await Task.Run(async () =>
        {
            ResultModel<T> resultModel = new ResultModel<T>();
            resultModel.data = await func.Invoke();
            resultModel.code = 1;
            await UserOperationLogAsync(operationLog);

            return resultModel;
        });
    }

    /// <summary>
    /// 执行有返回信息
    /// </summary>
    /// <param name="func"></param>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected ResultModel OperationExecuteCustom(Func<ResultModel> func, AddOperationLogInput? operationLog = null)
    {
        ResultModel resultModel = new ResultModel();

        resultModel = func.Invoke();
        if (resultModel.code == 0)
        {
            resultModel.code = 1;
        }
        if (resultModel.code == 1)
        {
            UserOperationLog(operationLog);
        }

        return resultModel;
    }
    /// <summary>
    /// 执行有返回信息
    /// </summary>
    /// <param name="func"></param>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected async Task<ResultModel> OperationExecuteCustomAsync(Func<Task<ResultModel>> func, AddOperationLogInput? operationLog = null)
    {
        return await Task.Run(async () =>
        {
            ResultModel resultModel = new ResultModel();

            resultModel = await func.Invoke();
            if (resultModel.code == 0)
            {
                resultModel.code = 1;
            }
            if (resultModel.code == 1)
            {
                await UserOperationLogAsync(operationLog);
            }

            return resultModel;
        });
    }
    /// <summary>
    /// 执行有返回信息
    /// </summary>
    /// <param name="func"></param>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected async Task<ResultModel<T>> OperationExecuteCustomAsync<T>(Func<Task<ResultModel<T>>> func, AddOperationLogInput? operationLog = null)
    {
        return await Task.Run(async () =>
        {
            ResultModel<T> resultModel = new ResultModel<T>();

            resultModel = await func.Invoke();
            if (resultModel.code == 0)
            {
                resultModel.code = 1;
            }
            if (resultModel.code == 1)
            {
                await UserOperationLogAsync(operationLog);
            }
            return resultModel;
        });
    }

    /// <summary>
	/// 用户操作日志(异步)
	/// </summary>
	/// <param name="operationLog"></param>
	/// <returns></returns>
	protected async Task UserOperationLogAsync(AddOperationLogInput? operationLog)
    {
        if (operationLog != null)
        {
            await Task.Run(() =>
            {
                OperationMqttLogRM log = new OperationMqttLogRM
                {
                    Account = CurrUser.Account,
                    Name = CurrUser.Name,
                    RoleName = CurrUser == null ? "超级管理员" : CurrUser.RoleName,
                    CommonType = (int)LogType.User,
                    Content = operationLog.Content
                };
                FmMqttClient fmMqttClient = new FmMqttClient();
                fmMqttClient.Publish(JsonConvert.SerializeObject(log));
            });
        }
    }

    /// <summary>
    /// 用户操作日志(同步)
    /// </summary>
    /// <param name="operationLog"></param>
    /// <returns></returns>
    protected void UserOperationLog(AddOperationLogInput? operationLog)
    {

        if (operationLog != null && CurrUser != null)
        {
            OperationMqttLogRM log = new OperationMqttLogRM
            {
                Account = CurrUser.Account,
                Name = CurrUser.Name,
                RoleName = CurrUser == null ? "超级管理员" : CurrUser.RoleName,
                CommonType = (int)LogType.User,
                Content = operationLog.Content
            };
            FmMqttClient fmMqttClient = new FmMqttClient();
            fmMqttClient.Publish(JsonConvert.SerializeObject(log));
        }
    }
}
